﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace NullCommander
{
    
    delegate void NavigateChangeEvent();
    
    class NavigateHistory
    {
        private List<string> history;
        
        private Int32 position;

        public NavigateHistory()
        {
            history = new List<string>();
            position = -1;
        }

        private void ChangePos(Int32 value)
        {
            position += value;
            if (OnNavigateChange != null)
                OnNavigateChange();
        }

        private String UpPath()
        {
            return System.IO.Path.GetDirectoryName(this.Path.ExcludePathDelimiter()).IncludePathDelimiter();
        }

        public Boolean CanBack()
        {
            return position > 0;
        }

        public Boolean CanForward()
        {
            return position < history.Count - 1;
        }

        public Boolean CanUp()
        {
            if (position < 0)
                return false;
            var path = UpPath();
            return path != null && UpPath() != String.Empty;
        }

        public void Back()
        {
            if (CanBack())
                ChangePos(-1);
        }

        public void Forward()
        {
            if (CanForward())
                ChangePos(1);
        }

        public void Up()
        {
            if (CanUp())
                Path = UpPath();
        }

        public String Path
        {
            get
            {
                if (position >= 0 && position < history.Count)
                    return history[position];
                else
                    return String.Empty;
            }
            set 
            {
                value = value.IncludePathDelimiter();
                // Текущий путь равен устанавливаемому значению.
                if (String.Compare(Path, value) == 0)
                    return;
                // Отсекаем историю после текущей позиции.
                if (CanForward())
                    history.RemoveRange(position + 1, history.Count - position - 1);
                history.Add(value);
                ChangePos(1);
            }
        }

        public Boolean IsValidPath
        {
            get { return Directory.Exists(Path); }
        }

        public event NavigateChangeEvent OnNavigateChange;

    }
}
